import ctypes
import win32api
import win32process
from win32con import PROCESS_ALL_ACCESS  # 权限
import psutil

class MemRead:
    def __init__(self, window_name):
        for proc in psutil.process_iter(['pid', 'name']):
            if proc.info['name'] == window_name:
                self.pid = proc.info['pid']
                self.hProcess = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, self.pid)  # 获取进程句柄
         # 获取进程的基地址
        self.base_address = win32process.EnumProcessModules(self.hProcess)[0]
        #print(self.base_address)
        
    def read(self, mem_address, data_len=4, data_type=''):
        if data_type == 'int':
            addr = ctypes.c_int32()
        elif data_type == 'float':
            addr = ctypes.c_float()
        elif data_type == 'double':
            addr = ctypes.c_double()
            data_len = 8
        elif data_type == 'str':
            buffer = ctypes.create_unicode_buffer(data_len)
            bytesRead = ctypes.c_size_t()
            if ctypes.windll.kernel32.ReadProcessMemory(int(self.hProcess), ctypes.c_void_p(mem_address), buffer, data_len * 2, ctypes.byref(bytesRead)):
                return buffer.value
            else:
                raise Exception("Failed to read memory")
        else:
            addr = ctypes.c_ulong()
        #print(hex(mem_address))
        # 句柄，地址，返回值，长度
        ctypes.windll.kernel32.ReadProcessMemory(int(self.hProcess), ctypes.c_void_p(mem_address), ctypes.byref(addr), data_len, None)
        # print(addr)
        return addr.value
